<script setup lang="ts">
import { useSocketStore } from "@/store/useSocket";
import { useRoute, useRouter } from "vue-router";
import { onMounted, onBeforeUnmount } from "vue";

useSeoMeta({
  title: "消息 - 技能猴子",
  ogTitle: "消息 - 技能猴子",
  description: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
  ogDescription: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
});

const route = useRoute();
const socketStore = useSocketStore();
const activeUser = ref(1);
socketStore.clearMessages();

const talkList = computed(() => socketStore.getTalkList);
const timer = ref(null);
onMounted(() => {
  socketStore.sendMessage("chatList", {}, (res) => {
    if (res.code === 200) {
      socketStore.setTalkList(res.data);
      // 如果当前浏览器链接中有to参数，需要根据参数做跳转
      const to = route.query.to;
      console.log("to", to);
      switch (to) {
        case "cs":
          const user = res.data.find((item) => item.uid === "IMservice");
          console.log("user", user);
          socketStore.setCurrentImKey(user.imKey);
          return;
      }
    }
  });

  timer.value = setInterval(() => {
    onlineReset();
  }, 5000);
});

// 刷新在线状态
const onlineReset = () => {
  const userIds = talkList.value
    .filter((item) => item.userType === 2)
    .map((item) => item.imKey);
  if (userIds.length === 0) return;
  socketStore.socket.emit("userOnline", userIds, (res) => {
    if (res.code === 200) {
      socketStore.setOnlineStatus(res.data);
    }
  });
};

onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
});
</script>

<template>
  <BaseHeaderMenuWhite bg-color="white" />
  <div class="body">
    <div class="chat">
      <div class="talk-list" v-if="talkList.length > 0">
        <ChatTalkUser
          v-for="item of talkList"
          :key="item._id"
          :talkItem="item"
          :activeUser="activeUser"
        />
      </div>
      <div class="chat-box" v-if="talkList.length > 0 && socketStore.currentImKey">
        <ChatWindow />
      </div>
      <div class="no-talk" v-if="talkList.length === 0">
        <el-empty description="暂无聊天记录" />
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.body {
  padding-top: 102px;
  background: #f9f9f9;
  height: 100vh;
  box-sizing: border-box;
}
.chat {
  width: 1200px;
  height: calc(100% - 30px);
  background: #ffffff;
  box-shadow: 0px 0px 16px 0px rgba(11, 13, 18, 0.06);
  border-radius: 16px 16px 16px 16px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  margin: 0 auto;
  display: flex;
  box-sizing: border-box;
}
.talk-list {
  flex: 0 0 260px;
  border-right: 1px solid #ededee;
  padding: 12px;
  box-sizing: border-box;
}
.chat-box {
  flex: 1;
}
.no-talk {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
